package com.sh.rbac.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.rbac.domain.converter.LoginLogConverter;
import com.sh.rbac.domain.dto.loginLog.LoginLogQueryDTO;
import com.sh.rbac.domain.entity.LoginLog;
import com.sh.rbac.domain.vo.loginLog.LoginLogEeVO;
import com.sh.rbac.domain.vo.loginLog.LoginLogVO;
import com.sh.rbac.exception.CustomException;
import com.sh.rbac.handler.LoginLogCellStyleHandler;
import com.sh.rbac.mapper.LoginLogMapper;
import com.sh.rbac.service.LoginLogService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @author lucky
 * @description 针对表【sys_login_log(登录日志记录表)】的数据库操作Service实现
 * @createDate 2024-07-01 20:35:59
 */
@Service
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog>
        implements LoginLogService {

    @Override
    public Page<LoginLogVO> getPage(Long current, Long limit, LoginLogQueryDTO loginLogQueryDTO) {
        // 创建 page 对象，传递当前页, 每页记录数
        Page<LoginLog> page = new Page<>(current, limit);

        // 条件参数
        String username = loginLogQueryDTO.getUsername();
        Integer loginStatus = loginLogQueryDTO.getLoginStatus();

        String startTime = null;
        String endTime = null;
        if (loginLogQueryDTO.getLoginTimes() != null) {
            startTime = loginLogQueryDTO.getLoginTimes()[0];
            endTime = loginLogQueryDTO.getLoginTimes()[1];
        }

        // 构建条件
        LambdaQueryWrapper<LoginLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(username), LoginLog::getUsername, username)
                .eq(loginStatus != null, LoginLog::getLoginStatus, loginStatus)
                .between(StrUtil.isNotBlank(startTime) && StrUtil.isNotBlank(endTime), LoginLog::getLoginTime, startTime, endTime);

        // 根据修改时间倒序
        queryWrapper.orderByDesc(LoginLog::getLoginTime);

        // 查询数据
        Page<LoginLog> loginLogPage = baseMapper.selectPage(page, queryWrapper);

        // 转换数据
        Page<LoginLogVO> loginLogVO = new Page<>();
        loginLogVO.setTotal(loginLogPage.getTotal());
        loginLogVO.setSize(loginLogPage.getSize());
        loginLogVO.setCurrent(loginLogPage.getCurrent());
        loginLogVO.setRecords(LoginLogConverter.INSTANCE.convertToLoginLogVOList(loginLogPage.getRecords()));
        loginLogVO.setPages(loginLogPage.getPages());

        return loginLogVO;
    }

    @Override
    public void exportData(Integer startCount, Integer endCount, HttpServletResponse response) {
        try {
            List<LoginLog> LoginLogs = baseMapper.selectList(new QueryWrapper<LoginLog>().last("limit " + startCount + "," + endCount));
            List<LoginLogVO> LoginLogVO = LoginLogConverter.INSTANCE.convertToLoginLogVOList(LoginLogs);

            // 设置 HTTP 响应内容类型
            response.setContentType("application/vnd.vnd.ms-excel");
            // 设置字符 HTTP 请求字符编码为 utf-8
            response.setCharacterEncoding("utf-8");
            // 设置文件名
            String fileName = URLEncoder.encode("登录日志-" + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_FORMAT) + RandomUtil.randomNumbers(5), StandardCharsets.UTF_8);
            // 设置 HTTP 请求响应头
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

            // 写入数据
            EasyExcel.write(response.getOutputStream())
                    .head(LoginLogEeVO.class)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("登录日志")
                    .registerWriteHandler(new LoginLogCellStyleHandler())
                    .doWrite(LoginLogVO);
        } catch (Exception e) {
            throw new CustomException("数据导出失败!");
        }
    }
}




